package com.lagou.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lagou.rpc.RpcRequest;
import com.lagou.rpc.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

public class UserClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    private ChannelHandlerContext context;
    //private String result;
    //private String para;
    private RpcResponse result;
    private RpcRequest para;


    public void channelActive(ChannelHandlerContext ctx) {
        context = ctx;
    }

    /**
     * 收到服务端数据，唤醒等待线程
     */

    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) {
        result = (RpcResponse) msg;
        notify();
    }

    /**
     * 写出数据，开始等待唤醒
     */

    public synchronized Object call() throws InterruptedException {
        context.writeAndFlush(para);
        wait();
        System.out.println("-------------------------\n 返回报文: \n"
                + JSON.toJSONString(result, SerializerFeature.PrettyFormat));
        return result.getResult();
    }

    /*
     设置参数
     */
    /*void setPara(String para) {
        this.para = para;
    }*/

    void setPara(RpcRequest para) {
        this.para = para;
    }

}
